package org.buptsse.thread;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;
import org.buptsse.entity.NearbyBookItem;
import org.buptsse.utils.APPConstant;
import org.buptsse.utils.ConnectionChecker;
import org.buptsse.utils.HttpHelper;
import org.buptsse.utils.JsonUtils;

import com.google.gson.reflect.TypeToken;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

public class GetNearbyBookListThread extends Thread {

	private Context context;
	private Handler handler;
	private String longtitude,latitude;
	private String distance;
	
	public GetNearbyBookListThread(Context context,Handler handler,String longtitude,String latitude,String distance)
	{
		this.context=context;
		this.handler=handler;
		this.longtitude=longtitude;
		this.latitude=latitude;
		this.distance=distance;
	}
	
	public void run()
	{
		if(ConnectionChecker.CheckConnection(context, handler)==false)
			return;
		ArrayList<NameValuePair> param=new ArrayList<NameValuePair>();
		param.add(new BasicNameValuePair("longtitude", longtitude));
		param.add(new BasicNameValuePair("latitude", latitude));
		param.add(new BasicNameValuePair("distance", distance));
		try {
			String json=HttpHelper.sendPost(APPConstant.getNearbyBookListUrl, param);
			if(json.contains("failure"))
			{
				Message msg=handler.obtainMessage(APPConstant.getNearbyBookListError);
				handler.sendMessage(msg);
				return;
			}else {
				LinkedList<NearbyBookItem> list=(LinkedList<NearbyBookItem>) JsonUtils.getJsonObject(json, new TypeToken<LinkedList<NearbyBookItem>>() {}.getType());
				Message msg=handler.obtainMessage(APPConstant.getNearbyBookListFinish);
				msg.obj=list;
				handler.sendMessage(msg);
				return;
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
